<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>消息中心</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../../layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../../layuiadmin/style/admin.css" media="all">
</head>
<body>

<div class="layui-fluid" id="LAY-app-message">
    <div class="layui-card">
        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <li>收到的消息<span class="layui-badge">1</span></li>
                <li>发私息</li>
                <li>发通知</li>
            </ul>
            <div class="layui-tab-content">
                <div class="layui-tab-item" id="recv-message">
                </div>
                <div class="layui-tab-item">
                    <div class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">发信人</label>
                            <div class="layui-input-block">
                                <input type="text" name="sendUserId" autocomplete="off" class="layui-input" readonly>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">收信人</label>
                            <div class="layui-input-block">
                                <select name="recvUserId" id="recvUserId" lay-search="">
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item layui-form-text">
                            <label class="layui-form-label">消息内容</label>
                            <div class="layui-input-block">
                                <textarea placeholder="请输入内容" class="layui-textarea" id="msg"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <button class="layui-btn" id="send-message">发送</button>
                        </div>
                    </div>
                </div>
                <div class="layui-tab-item">
                    <div class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">发信人</label>
                            <div class="layui-input-block">
                                <input type="text" name="sendUserId" autocomplete="off" class="layui-input" readonly>
                            </div>
                        </div>
                        <div class="layui-form-item layui-form-text">
                            <label class="layui-form-label">消息内容</label>
                            <div class="layui-input-block">
                                <textarea placeholder="请输入内容" class="layui-textarea" id="msgs"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <button class="layui-btn" id="send-messages">发送</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="../../layuiadmin/layui/layui.js"></script>
<!--收信人教师option选项模板-->
<script id="optionTeacherId" type="text/html">
    <option value="">教师</option>
    {{#  layui.each(d.data, function(index, teacher){  }}
    <option value="{{teacher.teacherId}}">
        {{teacher.teacherId}}： {{teacher.teacherName}}
    </option>
    {{#  }); }}
    {{#  if(d.data.length === 0){ }}
    无数据
    {{#  } }}
</script>

<!--收信人学生option选项模板-->
<script id="optionStudentId" type="text/html">
    <option value="">学生</option>
    {{#  layui.each(d.data, function(index, student){  }}
    <option value="{{student.studentId}}">
        {{student.studentId}}： {{student.studentName}}
    </option>
    {{#  }); }}
    {{#  if(d.data.length === 0){ }}
    无数据
    {{#  } }}
</script>
<script>
    layui.config({
        base: '../../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form', 'laytpl'], function () {
        let $ = layui.$;
        let form = layui.form;
        let setter = layui.setter;
        let laytpl = layui.laytpl;
        let socket;
        let sendUserId = JSON.parse(sessionStorage.getItem('user')).teacherId;
        // 建立socket连接
        // 初始化收信人信息
        $(function () {
            // // 建立socket连接
            if (typeof (WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                console.log("您的浏览器支持WebSocket");
                $("input[name='sendUserId']").val(sendUserId);
                let socketUrl = "ws://192.168.1.108:9999/daily_score_management/websocket/" + sendUserId;
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
                socket = new WebSocket(socketUrl);
                //打开事件
                socket.onopen = function () {
                    console.log("websocket已打开");
                };
                //获得消息事件
                socket.onmessage = function (msg) {
                    let serverMsg = "收到服务端信息：" + msg.data;
                    console.log(serverMsg);


                    let {sendUser, message} = JSON.parse(msg.data);
                    $('#recv-message').append("  <p style=\"width: 100%;height: 40px;margin: 2%;font-size: 16px\">" + sendUser + "发来了消息: " + message + "</p>")
                };
                //关闭事件
                socket.onclose = function () {
                    console.log("websocket已关闭");
                };
                //发生了错误事件
                socket.onerror = function (err) {
                    console.log(err);
                    console.log("websocket发生了错误");
                }
            }

            let htmlFull;
            // 初始化收信人信息
            $.ajax({
                url: setter.baseUrl + '/teacher/ins',
                dataType: "json",
                type: "get",
                contentType: 'application/json',
                xhrFields: {
                    withCredentials: true
                },
                success: function (res) {
                    if (res.code === 200) {
                        let getTpl = optionTeacherId.innerHTML;
                        laytpl(getTpl).render(res, function (html) {
                            htmlFull = html;
                        });
                        $.ajax({
                            url: setter.baseUrl + '/student/ins',
                            dataType: "json",
                            type: "get",
                            contentType: 'application/json',
                            xhrFields: {
                                withCredentials: true
                            },
                            success: function (res) {
                                if (res.code === 200) {
                                    let getTpl = optionStudentId.innerHTML
                                        , view = document.getElementById('recvUserId');
                                    laytpl(getTpl).render(res, function (html) {
                                        view.innerHTML = htmlFull + html;
                                    });
                                    form.render(); //更新全部
                                } else {
                                    layer.msg("失败");
                                }

                            },
                            error: function (e) {
                                layer.msg("失败");
                            }
                        });

                    } else {
                        layer.msg("失败");
                    }

                },
                error: function (e) {
                    layer.msg("失败");
                }
            });
        });


        //群发
        $('#send-messages').click(function () {
            if (typeof (WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                let msgs = document.getElementById('msgs').value;
                let webSocketMessageDto = '{"sendUserId":"' + sendUserId + '","message":"' + msgs + '","messageEnum":"all"}';
                console.log(webSocketMessageDto);
                socket.send(webSocketMessageDto);
            }
        });

        // 私发
        $('#send-message').click(function () {
            if (typeof (WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                let recvUserId = document.getElementById('recvUserId').value;
                let msg = document.getElementById('msg').value;
                let webSocketMessageDto = '{"recvUserId":"' + recvUserId + '","sendUserId":"' + sendUserId + '","message":"' + msg + '","messageEnum":"one"}';
                console.log(webSocketMessageDto);
                socket.send(webSocketMessageDto);
            }
        });


    });
</script>
</body>
</html>
